package com.think.oauth.user.security.token;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.security.auth.login.CredentialException;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.stereotype.Component;

import com.think.common.model.CustomUser;
import com.think.common.utils.JSonUtil;
import com.think.common.utils.NetUtils;
import com.think.common.utils.RandomUtils;
import com.think.oauth.user.service.CustomUserDetailsService;

public class ILabCustomTokenGranter extends AbstractCustomTokenGranter {

	private CustomUserDetailsService userDetailsService;
	public ILabCustomTokenGranter(AuthorizationServerTokenServices tokenServices,
			ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, CustomUserDetailsService userDetailsService,RedisTemplate redisTemplate) {
		super(tokenServices, clientDetailsService, requestFactory, "ilab");
		// TODO Auto-generated constructor stub
		this.userDetailsService = userDetailsService;
		this.redisTemplate = redisTemplate;
	}
	 private RedisTemplate redisTemplate;
	@Override
	protected UserDetails getUserDetails(Map<String, String> parameters){
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
		// TODO Auto-generated method stub
		String userName = tokenRequest.getRequestParameters().get("username");
		String pwd = tokenRequest.getRequestParameters().get("password");
		String appid = tokenRequest.getRequestParameters().get("appid");
		String appsecret = tokenRequest.getRequestParameters().get("appsecret");
		String nonce = RandomUtils.getRandomString("0123456789ABCDEF", 16);
		String cnonce = RandomUtils.getRandomString("0123456789ABCDEF", 16);
		String password = DigestUtils.sha256Hex(nonce + DigestUtils.sha256Hex(pwd).toUpperCase() +cnonce).toUpperCase();
		String signature = DigestUtils.md5Hex(nonce +cnonce+appid+appsecret).toUpperCase();
		Map<String, Object> map= JSonUtil.getJsonObj(NetUtils.doGet(String.format("http://202.205.145.156:8017/open/api/v2/user/validate?username=%s&password=%s&nonce=%s&cnonce=%s&appid=%s&signature=%s",userName,password,nonce,cnonce,appid,signature)));
		if ((Integer)map.get("code") == 0) {
			CustomUser userDetails = (CustomUser)this.userDetailsService.loadUserByIlabUsername(map.get("un").toString(),map.get("dis").toString(),map.get("access_token").toString());
			OAuth2Authentication auth2Authentication = new OAuth2Authentication(tokenRequest.createOAuth2Request(client), new UsernamePasswordAuthenticationToken(userDetails, "N/A",userDetails.getAuthorities()));
	        /*设置缓存*/
			auth2Authentication.setAuthenticated(true);
			auth2Authentication.setDetails(userDetails);
			return auth2Authentication;
		}
		else {
			 throw new InvalidGrantException("无法获取用户信息");
		}
	}
	
	

}
